package com.tony.business.controller;

import com.tony.business.util.RedisUtil;
import com.tony.business.util.curator.CuratorLock;
import com.tony.domain.bo.JsonResult;
import com.tony.domain.enumerate.ErrorEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author tony
 * @date 2020/3/8 11:46 上午
 */
@Api(tags = "测试")
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    RedisUtil redisUtil;

    @GetMapping("/testZookeeperLock")
    @ApiOperation(value = "test，zookeeper分布式锁", httpMethod = "GET")
    public JsonResult<?> testZookeeperLock() {
        JsonResult<?> jsonResult;
        InterProcessMutex interProcessMutex = null;
        try {
            interProcessMutex = CuratorLock.getLock(1, CuratorLock.PathEnum.LOCK);
            interProcessMutex.acquire();
            TimeUnit.SECONDS.sleep(1);
            jsonResult = new JsonResult<>();
        } catch (Exception exception) {
            exception.printStackTrace();
            jsonResult = new JsonResult<>(ErrorEnum._101006);
        } finally {
            try {
                assert interProcessMutex != null;
                if (interProcessMutex.isAcquiredInThisProcess()) {
                    interProcessMutex.release();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonResult;
    }

    @GetMapping("/testRedisLock")
    @ApiOperation(value = "test，redis分布式锁", httpMethod = "GET")
    public JsonResult<?> testRedisLock() throws InterruptedException {
//        String value = UUID.randomUUID().toString();
        String value = "aaa";
        System.out.println(Thread.currentThread().getName() + ",未锁定value==============================" + value);
        if (redisUtil.getLock("test", value, 60)) {
            System.out.println(Thread.currentThread().getName() + ",锁定value++++++++++++++++++++++++++++" + value);
            TimeUnit.SECONDS.sleep(3);
            //解锁
            redisUtil.releaseLock("test", value);
            return new JsonResult<>("锁定成功");
        } else {
            return new JsonResult<>(false, "锁定失败");
        }
    }


}
